package com.topcheer.yaml2Properties;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

/**
 * @author xutao
 * @Package com.topcheer.yaml2Properties
 * @Description: ${todo}
 * @date 2020/4/14 22:13
 */
public class TransformerImpl implements Transformer {
    private static final String ENCODING = "UTF-8";
    final String SEPARCTER = ".";

    public static void main(String[] args) {
//        testYml2Pro();
        testPro2Yml();
    }

    private static void testPro2Yml() {
        TransformerImpl transformer = new TransformerImpl();
        try {
            String s = FileUtils.readFileToString(new File("D:\\workspaces\\baseLine\\baseline-parent\\codeGen\\src\\main\\resource\\application.properties"), ENCODING);
            transformer.properties2Yaml("D:\\workspaces\\baseLine\\baseline-parent\\codeGen\\src\\main\\resource\\application.yml",s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void testYml2Pro() {
        TransformerImpl transformer = new TransformerImpl();
        try {
            String s = FileUtils.readFileToString(new File("D:\\workspaces\\baseLine\\baseline-parent\\cloud-provider-rbac\\src\\main\\resources\\application.yml"), ENCODING);
            List<String> strings = transformer.yml2Properties(s);
            strings.stream().forEach(System.out::println);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public List<String> yml2Properties(String s) {

        List<String> lines = new LinkedList<>();
        try {
            YAMLFactory yamlFactory = new YAMLFactory();
            YAMLParser parser = yamlFactory.createParser(s);
            String key = "";
            String value ;
            JsonToken token = parser.nextToken();
            while (token != null) {
                if (JsonToken.START_OBJECT.equals(token)) {
                    // "{" 表示字符串开头，不做解析
                } else if (JsonToken.FIELD_NAME.equals(token)) {
                    if (key.length() > 0) {
                        key = key + SEPARCTER;
                    }
                    key = key + parser.getCurrentName();
                    token = parser.nextToken();
                    if (JsonToken.START_OBJECT.equals(token)) {
                        continue;
                    }
                    value = parser.getText();
                    lines.add(key + "=" + value);
                    int dotOffset = key.lastIndexOf(SEPARCTER);
                    if (dotOffset > 0) {
                        key = key.substring(0, dotOffset);
                    }
                } else if (JsonToken.END_OBJECT.equals(token)) {
                    int dotOffset = key.lastIndexOf(SEPARCTER);
                    if (dotOffset > 0) {
                        key = key.substring(0, dotOffset);
                    } else {
                        key = "";
                        lines.add("");
                    }
                }
                token = parser.nextToken();
            }
            parser.close();
            return lines;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public File yml2Properties(File file) {
        return null;
    }

    @Override
    public void properties2Yaml(String filePath,String pros) {
        JsonParser parser = null;
        JavaPropsFactory factory = new JavaPropsFactory();
        try {
            parser = factory.createParser(pros);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            YAMLFactory yamlFactory = new YAMLFactory();
            YAMLGenerator generator = yamlFactory.createGenerator(
                    new OutputStreamWriter(new FileOutputStream(filePath), Charset.forName(ENCODING)));

            JsonToken token = parser.nextToken();

            while (token != null) {
                if (JsonToken.START_OBJECT.equals(token)) {
                    generator.writeStartObject();
                } else if (JsonToken.FIELD_NAME.equals(token)) {
                    generator.writeFieldName(parser.getCurrentName());
                } else if (JsonToken.VALUE_STRING.equals(token)) {
                    generator.writeString(parser.getText());
                } else if (JsonToken.END_OBJECT.equals(token)) {
                    generator.writeEndObject();
                }
                token = parser.nextToken();
            }
            parser.close();
            generator.flush();
            generator.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public File properties2Yaml(File file) {
        return null;
    }
}
